package com.saber;

import com.rabbitmq.client.*;
import com.saber.util.RabbitmqUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by PC on 2017/10/18.
 */
public class Work1 {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitmqUtil.buildConnection();
        final Channel channel = connection.createChannel();

        channel.queueDeclare(NewTask.TASK_QUEUE_NAME, true, false, false, null);
        System.out.println("Worker1  Waiting for messages");

        //每次从队列获取的数量
        channel.basicQos(1);

        final com.rabbitmq.client.Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Worker1  Received '" + message + "'");
                try {
//                    throw  new Exception();
                    doWork(message);
                }catch (Exception e){
                    channel.abort();
                }finally {
                    System.out.println("Worker1 Done");
                    channel.basicAck(envelope.getDeliveryTag(),false);
                    super.handleDelivery(consumerTag, envelope, properties, body);
                }
            }
        };
        boolean autoAck = false;
        //消息消费完成确认
        channel.basicConsume(NewTask.TASK_QUEUE_NAME,autoAck,consumer);
    }

    private static void doWork(String task){
        try {
            Thread.sleep(1000);//暂停1秒钟
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}
